<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="面试中一致性哈希算法被问到的概率非常大，本文将从如下三个方面探探一致性哈希算法，让大家轻松应对面试，并且说出宇宙不同的答案。  一致性哈希算法经典实用场景 一致性哈希算法通常不适合用于服务类负载均衡 面试应对之策">
<meta property="og:type" content="article">
<meta property="og:title" content="面试时遇到一致性哈希算法这样回答会让面试官眼前一亮">
<meta property="og:url" content="https://www.codingw.net/posts/ea6d8964.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="面试中一致性哈希算法被问到的概率非常大，本文将从如下三个方面探探一致性哈希算法，让大家轻松应对面试，并且说出宇宙不同的答案。  一致性哈希算法经典实用场景 一致性哈希算法通常不适合用于服务类负载均衡 面试应对之策">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210131165549182.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210131165606197.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210131165623526.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210131165643642.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210131165656914.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210131165708941.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210131165728345.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210101213844526.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="article:published_time" content="2021-02-02T14:39:36.000Z">
<meta property="article:modified_time" content="2021-04-26T10:01:14.637Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20210131165549182.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/ea6d8964.html"/>





  <title>面试时遇到一致性哈希算法这样回答会让面试官眼前一亮 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/ea6d8964.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">面试时遇到一致性哈希算法这样回答会让面试官眼前一亮</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-02-02T22:39:36+08:00">
                2021-02-02
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%9D%A2%E8%AF%95%E7%B3%BB%E5%88%97/" itemprop="url" rel="index">
                    <span itemprop="name">面试系列</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/ea6d8964.html" class="leancloud_visitors" data-flag-title="面试时遇到一致性哈希算法这样回答会让面试官眼前一亮">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>面试中一致性哈希算法被问到的概率非常大，本文将从如下三个方面探探一致性哈希算法，让大家轻松应对面试，并且说出宇宙不同的答案。</p>
<ul>
<li>一致性哈希算法经典实用场景</li>
<li>一致性哈希算法通常不适合用于服务类负载均衡</li>
<li>面试应对之策</li>
</ul>
<span id="more"></span>



<h2 id="1、一致性哈希算法经典使用场景"><a href="#1、一致性哈希算法经典使用场景" class="headerlink" title="1、一致性哈希算法经典使用场景"></a>1、一致性哈希算法经典使用场景</h2><p>在数据库存储领域如果单表数据量很大，通常会采用分库分表，同样在缓存领域同样需要分库，下面以一个非常常见的Redis分库架构为例进行阐述。<br><img src="https://img-blog.csdnimg.cn/20210131165549182.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>将上述3个Redis节点称之为分片，每一个节点存储部分数据，期间需要使用负载均衡算法，将数据尽量分摊到各个节点，充分发挥分布式的优势，提升系统缓存访问的性能。</p>
<p>在分布缓存领域，对数据存在新增与查询，即数据通过路由算法存储在某一个节点后，查询时需要尽量路由到同一个节点，否则会出现查询未命中缓存的情况，<strong>这也是与分布式服务调用领域的负载算法一个不同点。</strong></p>
<p>分布式缓存存储类领域的负载均衡算法通常会使用某一个字段当<strong>分片键</strong>，在进行负载之前先求出分片字段对应的HashCode，然后与当前的节点数取模。**即 hashcode(分片键) % 节点总数(分片总数)**。</p>
<h4 id="1-1-在分布式缓存领域上述算法的弊端"><a href="#1-1-在分布式缓存领域上述算法的弊端" class="headerlink" title="1.1 在分布式缓存领域上述算法的弊端"></a>1.1 在分布式缓存领域上述算法的弊端</h4><p>先哈希再驱魔实现起来简单高效，但在分布式缓存领域存在一个<strong>致命的痛点</strong>，对扩容、缩容不友好，会降低缓存的命中率。</p>
<p>因扩容引起的数据命中率问题示意图如下：<br><img src="https://img-blog.csdnimg.cn/20210131165606197.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>例如当前集群中由3个节点存储，例如现在向集群中写入6个数据，其分片键的hashcode为1-6，数据的分布情况如上述所示，但由于随着业务的急剧增长，3台redis已经无法满足业务的需求，项目组决定对其进行扩容，从原先的3台扩容到4台，这个时候项目组尝试去缓存中查找 k1,k2,k3,k4,k5,k6时会出现什么问题？</p>
<p>根据 hashcode 再取模的方式，由于数量从3台到4台，经路由算法路由后，k4 会尝试从3.169的机器去查找，但对应的数据却存储在3.166上，以上面6个key的命中来看，只有50%的命中率，扩容后带来<strong>缓存穿透</strong>，大量数据进入到后台数据库。</p>
<p>在数据存储领域的第一种解决方案：<strong>成倍扩容</strong>。将原来的3个节点数量扩充倍，新增加的第一台数据来源于第一台，以此类推，第6台的数据来源于第3台，这样k6经过新的负载均衡算法会落到第6台，数据原本存在于第3台，而第6台的数据来源于第3台，这样避免了<strong>缓存穿透</strong>。</p>
<p><strong>成倍扩容能有效解决扩容后带来的缓存穿透问题，但这样做会造成资源的浪费</strong>，有没有其他更好的方法呢？</p>
<p>一致性哈希算法闪亮登场。</p>
<h4 id="1-2-一致性哈希算法"><a href="#1-2-一致性哈希算法" class="headerlink" title="1.2 一致性哈希算法"></a>1.2 一致性哈希算法</h4><p>一致性哈希算法</p>
<p>一致性哈希算法的设计理念如下图所示：<br><img src="https://img-blog.csdnimg.cn/20210131165623526.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>首先将哈希值映射到 0 ~ 2的32次方的一个圆中，然后将实际的物理节点的IP地址或取其hash值，放入到hash环中。</p>
<p><strong>然后对需要插入的数据先求哈希，再顺时针沿着哈希环，找到第一个实际节点，数据将存储到该实际节点上。</strong></p>
<p>扩容后的示例图：<br><img src="https://img-blog.csdnimg.cn/20210131165643642.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>从中可以看到受影响的范围能控制在两个节点的hashcode之间的部分数据，比起先哈希再取模，其未命中率将会得到极大的影响。</p>
<p>但一致性哈希算法要得到较好的效果，取决于各个实体节点在哈希环的分布情况，是否能分散，例如如下分布则会大打折扣：<br><img src="https://img-blog.csdnimg.cn/20210131165656914.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>这种情况会造成数据分布不均衡，为了解决数据很可能分布不均匀的情况，对一致性哈希算法，提出了改进，引入了虚拟节点的，可以设置一个哈希环中存在多少个虚拟节点，然后将虚拟节点映射到实体节点，从而解决数据分布吧均衡的问题。<br><img src="https://img-blog.csdnimg.cn/20210131165708941.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>这样通过为不同的的实际节点映射不同的虚拟节点，实现数据的均匀分布，并且扩容或缩容时并不会出现大面积的缓存穿透。</p>
<blockquote>
<p>温馨提示：上述的映射只是一个理想状态，其核心思路是为每一个实体节点创建多个虚拟节点，并且核心虚拟节点的Hash值越分散越好。</p>
</blockquote>
<p>大家可以思考一下，如何用JAVA来实现一致性哈希算法？</p>
<p>一致性哈希算法的两个关键：</p>
<ul>
<li><p>顺时针选择节点<br>可以使用TreeMap，一来具备排序功能，天然提供了相应的方法获取顺时针的一个元素。<br><strong>TreeMap 的 ceilingEntry()方法</strong>用于返回与大于或等于给定键元素(ele)的最小键元素链接的键值对。</p>
</li>
<li><p>虚拟节点如何生成分散的哈希值<br>生成分散的哈希值，通常可以基于md5加密算法来实现。<br><img src="https://img-blog.csdnimg.cn/20210131165728345.png#pic_center" alt="在这里插入图片描述"></p>
<h2 id="2、一致性哈希算法被“滥用”"><a href="#2、一致性哈希算法被“滥用”" class="headerlink" title="2、一致性哈希算法被“滥用”"></a>2、一致性哈希算法被“滥用”</h2></li>
</ul>
<p>一致性哈希算法在面对分布式缓存有着得天独厚的优势，因为它的产生就是为了解决分布式缓存扩容、缩容带来的缓存穿透问题。但现在一致性在分布式服务调用的负载算法竟然也引入了一致性哈希算法。</p>
<p>在Dubbo中为了实现客户端在服务调用时对服务提供者进行负载均衡，官方也提供了一致性哈希算法；在RocketMQ集群消费模式时消费队列的负载均衡机制竟然也实现了一致性哈希算法，<strong>但我觉得一致性哈希算法在这些领域完全无法发挥其他优势，比轮循、加权轮循、随机、加权随机算法等负载均衡算法相比，实现复杂，性能低下，运维管理复杂</strong>。</p>
<p>因为在服务调用等负载均衡算法，<strong>多次服务调用之间关联性不太强</strong>，在服务端扩容、缩容后，对于客户端来说其实并不关心路由到哪台服务器，其关心的是能否返回一台服务器即可。</p>
<h2 id="3、面试应对之策"><a href="#3、面试应对之策" class="headerlink" title="3、面试应对之策"></a>3、面试应对之策</h2><p>在面试过程中，遇到一致性哈希算的时候，尽量能从其使用场景：<strong>分布式缓存负载均衡</strong>，特别是突出<strong>扩容、缩容能有效避免缓存穿透的问题</strong>。同时需要阐述一致性哈希算法的缺陷以及其应对策略(虚拟节点)。</p>
<p>聊的差不多可以顺便提一下阅读过一致性哈希算法的源码：强调TreeMap与虚拟节点哈希值的生成方法。</p>
<p>最后可以尝试引导面试官聊聊现在一致性哈希算法有点被滥用的嫌疑，在轻松愉快的讨论中与面试交流技术，面试官好评度蹭蹭往上涨。</p>
<hr>
<p>欢迎加笔者微信号(<strong>dingwpmz</strong>)，拉您如技术交流加群探讨，关注『中间件兴趣圈』回复<strong>【PDF】</strong>可获取海量学习资料。<br><img src="https://img-blog.csdnimg.cn/20210101213844526.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"></p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/76ab8a6b.html" rel="next" title="Netty进阶：手把手教你如何编写一个NIO客户端">
                <i class="fa fa-chevron-left"></i> Netty进阶：手把手教你如何编写一个NIO客户端
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/381d8256.html" rel="prev" title="Netty进阶：手把手教你如何编写一个NIO服务端">
                Netty进阶：手把手教你如何编写一个NIO服务端 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E4%B8%80%E8%87%B4%E6%80%A7%E5%93%88%E5%B8%8C%E7%AE%97%E6%B3%95%E7%BB%8F%E5%85%B8%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-number">1.</span> <span class="nav-text">1、一致性哈希算法经典使用场景</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-%E5%9C%A8%E5%88%86%E5%B8%83%E5%BC%8F%E7%BC%93%E5%AD%98%E9%A2%86%E5%9F%9F%E4%B8%8A%E8%BF%B0%E7%AE%97%E6%B3%95%E7%9A%84%E5%BC%8A%E7%AB%AF"><span class="nav-number">1.0.1.</span> <span class="nav-text">1.1 在分布式缓存领域上述算法的弊端</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-%E4%B8%80%E8%87%B4%E6%80%A7%E5%93%88%E5%B8%8C%E7%AE%97%E6%B3%95"><span class="nav-number">1.0.2.</span> <span class="nav-text">1.2 一致性哈希算法</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81%E4%B8%80%E8%87%B4%E6%80%A7%E5%93%88%E5%B8%8C%E7%AE%97%E6%B3%95%E8%A2%AB%E2%80%9C%E6%BB%A5%E7%94%A8%E2%80%9D"><span class="nav-number">2.</span> <span class="nav-text">2、一致性哈希算法被“滥用”</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3%E3%80%81%E9%9D%A2%E8%AF%95%E5%BA%94%E5%AF%B9%E4%B9%8B%E7%AD%96"><span class="nav-number">3.</span> <span class="nav-text">3、面试应对之策</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
